package br.com.rapidrest.chain;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.util.RedirectUtil;

public class PageRedirectCommand implements Command {

	@Override
	@SuppressWarnings("unchecked")
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		Object returnedValue = context.getReturnedValue();

		if (returnedValue instanceof Class) {
			String webPackage = context.getWebPackage();
			Class<?> pageClass = (Class<?>) returnedValue;
			if (pageClass.getName().startsWith(webPackage)) {
				HttpServletRequest request = context.getRequest();
				String requestURI = request.getRequestURI();
				String contextPath = request.getContextPath();
				requestURI = requestURI.replace(contextPath, "");
				
				String targetMapping = RedirectUtil.getMapping(webPackage,
						pageClass);

				String redirectUri = RedirectUtil.resolveUri(requestURI,
						targetMapping);

				HttpServletResponse response = context.getResponse();
				try {
					response.sendRedirect(redirectUri);
				} catch (IOException e) {
					throw new ChainException(e);
				}
				return;
			}
		}

		chain.proceed();
	}

}
